//
//  GameManager.m
//  MyPopStar
//
//  Created by tarena on 16/1/6.
//  Copyright © 2016年 ssnb. All rights reserved.
//

#import "GameManager.h"
#import "StarCalculation.h"

@interface GameManager ()<StarGroupViewDelegate>

@property (nonatomic,strong) StarGroupView *starsView;
@property (nonatomic,strong) allStarArray starsModelGroup;
@property (nonatomic,strong) chooseArray chooseGroup;
@property (nonatomic,assign) NSInteger score;
@property (nonatomic,assign) NSInteger targetScore;
@property (nonatomic,assign) NSInteger leavel;
@property (nonatomic,strong) NSArray *targetArr;
@property (nonatomic,assign) NSInteger bestScore;
@end
@implementation GameManager
mdealloc

#pragma mark -- 游戏界面
-(StarGroupView *)getGameView{
    return  [self starsView];
}
- (StarGroupView *)starsView {
	if(_starsView == nil) {
        _starsView = [[StarGroupView alloc] init];
        _starsView.delegate = self;
    }
	return _starsView;
}

-(void)saveData{
    [StarCalculation saveResumGameArray:self.starsModelGroup];
    
    NSString *filePath = [DocumentPath stringByAppendingPathComponent:@"ugameinfo"];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[NSNumber numberWithInteger:self.score] forKey:@"score"];
    [dic setObject:[NSNumber numberWithInteger:self.targetScore] forKey:@"targetScore"];
    [dic setObject:[NSNumber numberWithInteger:self.leavel] forKey:@"leavel"];
    [dic writeToFile:filePath atomically:YES];
    
}
#pragma mark -- 游戏开始,清理资源
-(void)clean{
    NSString *filePath = [DocumentPath stringByAppendingPathComponent:@"bestScore"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    self.bestScore =[[dic objectForKey:@"bestScore"] integerValue];
    [self.delegate GameManager:self bestScore:self.bestScore];
    self.starsModelGroup = nil;
    self.chooseGroup = nil;
    [self.starsView clean];
}
-(void)resumStatus{
    //获取到的数据里的对象内容
    
    NSString *filePath = [DocumentPath stringByAppendingPathComponent:@"ugameinfo"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    [self leavelAndTarget:[[dic objectForKey:@"leavel"] integerValue]];
    self.score=[[dic objectForKey:@"score"] integerValue];
    [self.delegate GameManager:self GameScore:self.score];
}
-(void)leavelAndTarget:(NSInteger)leavel{
    self.leavel =leavel;
    self.targetScore =[[self.targetArr objectAtIndex:self.leavel] integerValue];
    [self.delegate GameManager:self GameLevel:self.leavel];
    [self.delegate GameManager:self GameTargetScore:self.targetScore];
}
-(void)newStatus{
    [self leavelAndTarget:1];
    self.score = 0;
    [self.delegate GameManager:self GameScore:self.score];
}
-(void)passStatus{
    self.leavel++;
    [self leavelAndTarget:self.leavel];
    [self.delegate GameManager:self GameScore:self.score];
}
#pragma mark ---开始游戏

-(void)startWithType:(StartType)type{
    [self clean];//清理数据
    //判断类型用于初始化的一些配置
    switch (type) {
        case StartTypeResum:
            [self resumStatus];
            self.starsModelGroup = [StarCalculation getResumGameArray];
            break;
        case StartTypeNew:
            [self newStatus];
            self.starsModelGroup = [StarCalculation getInitGameArray];
            break;
        default:
            [self passStatus];
            self.starsModelGroup = [StarCalculation getInitGameArray];
            break;
    }
    //将获取到的数组传入到starsView中
    [self.starsView addStarsModelGroup:self.starsModelGroup];
}

#pragma mark -- StarGroupViewDelegate
-(void)starGroupView:(StarGroupView *)view touchPoint:(StarPoint)point{
    //1 判断是否有选中过
    if(self.chooseGroup!=nil||self.chooseGroup>0){
        //点击的点是否在选中列表中
        if ([self.chooseGroup containsObject:[[self.starsModelGroup objectAtIndex:point.column] objectAtIndex:point.row]]) {
            [self removestar];
            return;
        }
        //不在列表中就重置属性
        [self huanyuan];
        self.chooseGroup=nil;
    }
    
    //1 判断是否可以消除
    if([StarCalculation canChoose:self.starsModelGroup atPoint:point]){
        //1.1返回可以消除的点
        self.chooseGroup = [StarCalculation connectedStarModel:self.starsModelGroup atPoint:point];
        //1.2将可消除的点发送给对象,进行缩放
        [self.starsView animationWithArray:self.chooseGroup andStatus:NO];

    }

}
-(void)removestar{
    self.starsView.userInteractionEnabled=NO;
    //在选中列表中,触发删除动作
    self.starsModelGroup = [StarCalculation clean:self.starsModelGroup and:self.chooseGroup];
    //更新视图
    {
        self.score += [StarCalculation scoreWithNumber:self.chooseGroup.count];
        [self.delegate GameManager:self GameScore:self.score];
        [self updateBestScore];
    }
    
    [self.starsView updateViewWithd:self.starsModelGroup andRemoveStarModelGroup:self.chooseGroup];
    
    if([StarCalculation canMoveLeft:self.starsModelGroup]){
        self.starsModelGroup = [StarCalculation moveLeft:self.starsModelGroup];
        //更新视图
        [self.starsView updateViewWith:self.starsModelGroup];
    }
    
    self.chooseGroup = nil;
    self.starsView.userInteractionEnabled=YES;
    
    if([self isGameVoer]){
        self.score+=[StarCalculation gameOverScore:self.starsView.subviews.count];//分数结算
        [self updateBestScore];
        [self.delegate GameManager:self GameScore:self.score];
        [self.starsView Over];//进行结算动画
    }
    return;

}

-(void)starGroupView:(StarGroupView *)view updateOver:(BOOL)isOver{
    if (isOver) {
//        MyLog(@"更新视图结束");
    }
}
-(void)starGroupView:(StarGroupView *)view {}
-(void)starGroupView:(StarGroupView *)view overAnimationOver:(BOOL)isOver{
    if (isOver) {
        if (self.score >self.targetScore) {//对分数进行判断
            [self.delegate GameManager:self GameOverStatus:GameStatusPass];
        }else{
            //如果得分超过xxx就返回Pass,否者返回Over
            [self.delegate GameManager:self GameOverStatus:GameStatusOver];
        }
    }
}
/**
 *  @author ssnb, 16-01-13 20:01:05
 *
 *  判断并更新最高分
 */
-(void)updateBestScore{
    if (self.score>self.bestScore) {
        self.bestScore = self.score;
        [self.delegate GameManager:self bestScore:self.bestScore];
        
        NSString *filePath = [DocumentPath stringByAppendingPathComponent:@"bestScore"];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:[NSNumber numberWithInteger:self.bestScore] forKey:@"bestScore"];
        [dic writeToFile:filePath atomically:YES];
    }
}
#pragma mark -- 改变选项时恢复数据

-(void)huanyuan{
    for (StarModel *model in self.chooseGroup) {
        model.choose=NO;
    }
    [self.starsView animationWithArray:self.chooseGroup andStatus:YES];
}
#pragma mark --判断是否死亡
/**
 *  @author ssnb, 16-01-13 20:01:59
 *
 *  游戏是否结束
 *
 *  @return YES 表示游戏结束
 */
-(BOOL)isGameVoer{
    for (columnArray column in self.starsModelGroup) {
        for (StarModel *mo in column) {
            if([StarCalculation canChoose:self.starsModelGroup atPoint:mo.starPoint]){
                return NO;
            };
        }
    }
    return YES;
}
#pragma mark -- 离开游戏释放资源
-(void)over{
    self.starsView=nil;
    self.starsModelGroup =nil;
    self.chooseGroup=nil;
    self.targetArr =nil;
}

- (NSArray *)targetArr {
    if(_targetArr == nil) {
        NSString *str = [[NSBundle mainBundle] pathForResource:@"target" ofType:@"plist"];
        _targetArr =  [NSArray arrayWithContentsOfFile:str];
	}
	return _targetArr;
}

@end
